from openpyxl import Workbook, load_workbook
import os
import logging


class CreateExcel:
    """
    调用insert_feed_back的时候需要添加的字段:
    fbTitle
    fbTime
    fbContent
    """
    def __init__(self, path=r'/Users/duanhongtao/Desktop/feedback.xlsx'):
        # 用户反馈包含字段, 如果要添加新字段，添加按下列各式添加:
        # 列id:['列标题','列数据传参字段']
        _ = ['create_time', 'id', 'app_id', 'device_id', 'content', 'label3', 'network_type',
         'platform', 'channel']
        self.fb_domain = {
            # 'A': ['问题标题', 'fbTitle'],
            # 'B': ['反馈时间', 'fbTime'],
            # 'C': ['反馈内容', 'fbContent'],
            # 'D': ['设备型号', 'fbPhoneType']
            'A': ['反馈创建时间', 'create_time'],
            'B': ['反馈Id', 'id'],
            'C': ['应用Id', 'app_id'],
            'D': ['反馈内容', 'content'],
            'E': ['问题归类', 'label3'],
            'F': ['网络类型', 'network_type'],
            'G': ['设备平台', 'platform'],
            'H': ['应用渠道', 'channel'],
            'I': ['设备Id', 'device_id']
        }
        self.path = path
        logging.basicConfig(level='DEBUG')

        if not os.path.exists(self.path):
            logging.info('未找找到置顶路径，开始创建文件')
            try:
                self.feed_back_excel = Workbook().save(self.path)
            except Exception as e:
                logging.error('创建文件失败，错误原因: {}'.format(e))
            else:
                logging.info('用户反馈表创建成功')

        else:
            self.feed_back_excel = load_workbook(self.path)

    # 添加用户反馈title，需向sheet添加用户反馈时调用，保证为最新的title样式
    def _insert_row_title(self):

        for title in self.fb_domain:
            self.fb_ws[title + '1'] = self.fb_domain[title][0]

    # 添加用户反馈函数
    def insert_feed_back(self, sheet_name='用户反馈', **kwargs):
        try:
            self.fb_ws = self.feed_back_excel.get_sheet_by_name(sheet_name)
            logging.info('找到{}用户反馈表格'.format(sheet_name))

        except KeyError:
            logging.info('没有找到用户反馈表格名称: {}，开始创建'.format(sheet_name))
            self.fb_ws = self.feed_back_excel.create_sheet(sheet_name, 0)

        except Exception as e:
            logging.info('出现其他异常，错误原因: {}'.format(e))

        finally:
            self._insert_row_title()
            fb_count = self.fb_ws.max_row
            logging.warning('准备添加新的用户反馈内容')
            for fb_content in self.fb_domain:
                try:
                    self.fb_ws[fb_content+str(fb_count+1)] = kwargs[self.fb_domain[fb_content][1]]

                except KeyError as e:
                    logging.warning(' insert_feed_back 方法确少关键字传参: {}'.format(e))

                except Exception as e:
                    logging.error('添加新的用户失败， 错误原因: {}'.format(e))

                else:
                    self.feed_back_excel.save(self.path)


if __name__ == '__main__':
    fb = CreateExcel()
    # 将接口字段整理成字典传给insert_feed_back
    fb_content_params = {
        'fbTitle': '报错',
        'fbTime': '2019.01.01 19:00:00',
        'fbContent': '无法充值',
        'fbPhoneType': 'IOS'
    }
    fb.insert_feed_back(**fb_content_params)
